﻿using TradePublish.Common;
using log4net;
using TradePublish.Service;
using System;
using System.Data;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Collections;

namespace TradePublish.Dao
{
    public class DissentTradeDao
    {
        private ILog log = null;

        public DissentTradeDao()
        {
            this.log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        }

        public DataSet findTopUnGraspImg(int length, StringBuilder expIds)
        {
            string str = "";
            if ((expIds != null) && (expIds.Length > 0))
            {
                String[] ids = expIds.ToString().Split(',');
                for (int xx = 0; xx < ids.Length; xx ++ )
                {
                    if (ids[xx] == null || ids[xx].Equals(""))
                        continue;
                    str += " and id<>" + ids[xx];
                }
               // str = " and id not in (" + expIds.Remove(expIds.Length - 1, 1).ToString() + ") ";
            }
            string commandText = string.Concat(new object[] { " select  * from (select reg_no ,CLASS_NO from  DISSENT_TRADE WHERE (HAS_GRASP_IMAGE=0 or HAS_GRASP_IMAGE is null ) ", str, " order by  ID DESC  ) where ROWNUM<=" + length + " order by ROWNUM asc" });
            DataSet set = new DataSet();
            while (true)
            {
                if (DateTime.Now.Hour == 6 && DateTime.Now.Minute < 30)
                {
                    Thread.Sleep(180000);//3fenzhong  
                    continue;
                }
                DatabaseHelper dbh = new DatabaseHelper();
                try
                {
                    set = dbh.ExecuteDataSet(commandText);
                    if (((set.Tables == null) || (set.Tables[0].Rows == null)) || (set.Tables[0].Rows.Count == 0))
                    {
                        this.log.Info("读取数据库表DISSENT_TRADE，获得尚未采集商标图片的商标0个.");
                        return set;
                    }
                    this.log.Info("读取数据库表DISSENT_TRADE，获得尚未采集商标图片的商标" + set.Tables[0].Rows.Count + "个.");
                    return set;
                }
                catch (Exception exception)
                {
                    this.log.Error("读取数据库表DISSENT_TRADE，获得尚未采集商标图片异常", exception);
                    Thread.Sleep(0x1388);
                }
                finally
                {
                    dbh.Dispose();
                }
            }
        }

        public ArrayList findUnSearchEmailTask()
        {
            ArrayList rtn = new ArrayList();
            DataSet set = new DataSet();
            String sql = "select *  from (select id, apply_user_name  from dissent_trade where length( apply_user_name) > 3  and (HAS_SEARCH_EMAIL = 0 or HAS_SEARCH_EMAIL is null) order by trade_publish_issue desc ) where rownum <50 order by ROWNUM asc";
            while (true)
            {
                if (DateTime.Now.Hour == 6 && DateTime.Now.Minute < 30)
                {
                    Thread.Sleep(180000);//3fenzhong  
                    continue;
                }
                DatabaseHelper dbh = new DatabaseHelper(); 
                try
                {
                    dbh.BeginTransaction();
                    set = dbh.ExecuteDataSet(sql,TradePublish.Service.ConnectionState.KeepOpen);
                    if(set == null || set.Tables == null || set.Tables.Count == 0 || set.Tables[0].Rows == null || set.Tables[0].Rows.Count == 0){
                        //无数据
                        dbh.CommitTransaction();
                        this.log.Info("读取数据库表dissent_trade，获得本次未采集邮箱的申请人名称任务0个.");
                        return null;
                    }
                    this.log.Info("读取数据库表dissent_trade，获得本次需采集邮箱的申请人名称任务" + set.Tables[0].Rows.Count + "个.");
                    //有数据。
                    StringBuilder updateSql = new StringBuilder("update dissent_trade set HAS_SEARCH_EMAIL = 2 where ");
                    for (int i = 0; i < set.Tables[0].Rows.Count;i++ )
                    {
                        rtn.Add(set.Tables[0].Rows[i][1].ToString());
                        if (i != 0)
                        {
                            updateSql.Append(" or ");
                        }
                        updateSql.Append(" id=").Append(set.Tables[0].Rows[i][0].ToString());
                    }
                    dbh.ExecuteNonQuery(updateSql.ToString(),TradePublish.Service.ConnectionState.KeepOpen);
                    return rtn;
                }
                catch (Exception exception)
                {
                     dbh.RollbackTransaction();  
                    this.log.Error("读取数据库表dissent_trade，获得本次的未采集邮箱的申请人名称时发送异常", exception);
                }
                finally
                {
                    dbh.Dispose();
                }
                Thread.Sleep(300000); 
            }
        }

        public void setHasGraspImage(string regNo, bool hasGrasped)
        {
            string commandText = "update  DISSENT_TRADE  set HAS_GRASP_IMAGE=1  WHERE reg_no='" + regNo + "'";
            string str2 = "INSERT INTO  DISSENT_TRADE_GRASPED_IMG (id,Dissent_reg_no) VALUES(gen_sequence.nextval,'" + regNo + "')";
            while (true)
            {
                if (DateTime.Now.Hour == 6 && DateTime.Now.Minute < 30)
                {
                    Thread.Sleep(180000);//3fenzhong  
                    continue;
                }
                DatabaseHelper dbh = new DatabaseHelper();
                try
                {
                    dbh.ExecuteNonQuery(  commandText );
                    if (!hasGrasped)
                    {
                        dbh.ExecuteNonQuery ( str2 );
                    }
                    return;
                }
                catch (Exception exception)
                {
                    this.log.Error("保存数据库表DISSENT_TRADE，设置已采集图片异常", exception);
                    Thread.Sleep(0x1388);
                }
                finally
                {
                    dbh.Dispose();
                }
            }
        }

        public void setHasSearchEmail(string applyUserNames)
        {
            string commandText = " update dissent_trade SET  HAS_SEARCH_EMAIL = 1  where APPLY_USER_NAME ='" + applyUserNames.Replace("'", "''") + "' ";
            DataSet set = new DataSet();
            while (true)
            {
                if (DateTime.Now.Hour == 6 && DateTime.Now.Minute < 30)
                {
                    Thread.Sleep(180000);//3fenzhong  
                    continue;
                }
                DatabaseHelper dbh = new DatabaseHelper();
                try
                {
                    dbh.ExecuteNonQuery (commandText);
                    return;
                }
                catch (Exception exception)
                {
                    this.log.Error("设置申请人的邮箱已采集异常，dissent_trade", exception);
                }
                finally
                {
                    dbh.Dispose();
                }
                Thread.Sleep(0x1388);
            }
        }

        public bool verifyHasGrasped(string regNo)
        {
            string commandText = " select count(ID) from DISSENT_TRADE_GRASPED_IMG where Dissent_reg_no='" + regNo + "'";
            while (true)
            {
                if (DateTime.Now.Hour == 6 && DateTime.Now.Minute < 30)
                {
                    Thread.Sleep(180000);//3fenzhong  
                    continue;
                }
                DataSet set = new DataSet();
                DatabaseHelper dbh = new DatabaseHelper();
                try
                {
                    set = dbh.ExecuteDataSet( commandText);

                    if (set.Tables != null && set.Tables.Count > 0 && set.Tables[0].Rows.Count > 0 && Convert.ToInt32(set.Tables[0].Rows[0][0]) > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception exception)
                {
                    this.log.Error("验证某注册号是否已采集图片，内部异常.", exception);
                    Thread.Sleep(0x1388);
                }
                finally
                {
                    dbh.Dispose();
                }
            }
        }
    }
}
